package com.heima.Interceptor;

import com.heima.Config.ThreadUtil;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class Interceptor implements HandlerInterceptor {
//    在微服务方法执行前运行
//    获取token里面的用户id并把它传到微服务
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token!=null)
        {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            Object id = claimsBody.get("id");
            WmUser wmUser=new WmUser();
            wmUser.setId((Integer) id);
            ThreadUtil.SetThread(wmUser);
        }
        return true;
    }

    //    在微服务方法执行后运行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, @Nullable ModelAndView modelAndView) throws Exception {
//        删除线程里的数据
        ThreadUtil.threadLocal.remove();
    }

}
